<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Challenge.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_Model_Challenge extends Core_Model_Item_Abstract {
	protected $_owner_type = 'user';
	
	protected $_type = 'vote_challenge';
	
	protected $_participants;
	
	public function getShortType() {
		return 'challenge';
	}
	
	public function _postInsert() {
		parent::_postInsert ();
		
		// Create auth stuff
		$context = $this->api ()->authorization ()->context;
		$context->setAllowed ( $this, 'everyone', 'view', true );
		$context->setAllowed ( $this, 'registered', 'comment', true );
	}
	
	public function getTagLinks() {
		$tags = explode ( ',', $this->keywords );
		$html = array ();
		
		foreach ( $tags as $tag ) {
			$tag = trim ( $tag );
			$html [] = "<a href='javascript:void(0)' onclick='tagAction(\"{$tag}\")'>{$tag}</a>";
		}
		
		return implode ( ' - ', $html );
	}
	
	public function setPhoto($photo) {
		if ($photo instanceof Zend_Form_Element_File) {
			$file = $photo->getFileName ();
		} else if (is_array ( $photo ) && ! empty ( $photo ['tmp_name'] )) {
			$file = $photo ['tmp_name'];
		} else if (is_string ( $photo ) && file_exists ( $photo )) {
			$file = $photo;
		} else {
			throw new Event_Model_Exception ( 'invalid argument passed to setPhoto' );
		}
		
		$this->removePhotos ();
		
		$name = basename ( $file );
		$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
		$params = array ('parent_id' => $this->getIdentity (), 'parent_type' => 'vote_challenge' );
		
		// Save
		$storage = Engine_Api::_ ()->storage ();
		
		// Resize image (main)
		$image = Engine_Image::factory ();
		$image->open ( $file )->resize ( 720, 720 )->write ( $path . '/m_' . $name )->destroy ();
		
		// Resize image (profile)
		$image = Engine_Image::factory ();
		$image->open ( $file )->resize ( 200, 400 )->write ( $path . '/p_' . $name )->destroy ();
		
		// Resize image (normal)
		$image = Engine_Image::factory ();
		$image->open ( $file )->resize ( 144, 144 )->write ( $path . '/in_' . $name )->destroy ();
		
		// Resize image (icon)
		$image = Engine_Image::factory ();
		$image->open ( $file );
		
		$size = min ( $image->height, $image->width );
		$x = ($image->width - $size) / 2;
		$y = ($image->height - $size) / 2;
		
		$image->resample ( $x, $y, $size, $size, 48, 48 )->write ( $path . '/is_' . $name )->destroy ();
		
		// Store
		$iMain = $storage->create ( $path . '/m_' . $name, $params );
		$iProfile = $storage->create ( $path . '/p_' . $name, $params );
		$iIconNormal = $storage->create ( $path . '/in_' . $name, $params );
		$iSquare = $storage->create ( $path . '/is_' . $name, $params );
		
		$iMain->bridge ( $iProfile, 'thumb.profile' );
		$iMain->bridge ( $iIconNormal, 'thumb.normal' );
		$iMain->bridge ( $iSquare, 'thumb.icon' );
		
		// Remove temp files
		@unlink ( $path . '/p_' . $name );
		@unlink ( $path . '/m_' . $name );
		@unlink ( $path . '/in_' . $name );
		@unlink ( $path . '/is_' . $name );
		
		// Update row
		$this->modified_date = date ( 'Y-m-d H:i:s' );
		$this->photo_id = $iMain->file_id;
		$this->save ();
		
		return $this;
	}
	
	public function getCategory() {
		if (isset ( $this->category_name )) {
			return $this->category_name;
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'categories', 'vote' );
		$name = $table->info ( 'name' );
		
		$select = $table->select ()->setIntegrityCheck ( false )->from ( $name, array ('category_name' ) )->where ( 'category_id = ?', $this->category_id );
		
		return $table->getAdapter ()->fetchOne ( $select );
	}
	
	public function getSlug() {
		return $this->slug;
	}
	
	public function getHref($params = array()) {
		$params = array_merge ( array ('route' => 'vote_profile', 'reset' => true, 'id' => $this->getSlug () ), $params );
		
		$route = $params ['route'];
		$reset = $params ['reset'];
		unset ( $params ['route'] );
		unset ( $params ['reset'] );
		
		return Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( $params, $route, $reset );
	}
	
	public function getParticipants($params = array()) {
		if (! $this->_participants) {
			$pTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
			$params ['challenge_id'] = $this->getIdentity ();
			$select = $pTable->getSelect ( $params );
			
			if ($this->type == 'video') {
				$select->where ( 'status = 1' );
			}
			
			$paginator = Zend_Paginator::factory ( $select );
			
			if (! empty ( $params ['ipp'] )) {
				$paginator->setItemCountPerPage ( $params ['ipp'] );
			}
			
			if (! empty ( $params ['page'] )) {
				$paginator->setCurrentPageNumber ( $params ['page'] );
			}
			
			$this->_participants = $paginator;
		}
		
		return $this->_participants;
	}
	
	public function getMostPopular($limit = 3) {
		if (! $limit) {
			return array ();
		}
		
		$pTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		
		$select = $pTable->select ()->where ( 'view_count > 0' )->where ( 'challenge_id = ?', $this->getIdentity () )->order ( 'view_count DESC' )->limit ( $limit );
		
		return Zend_Paginator::factory ( $select );
	}
	
	public function getMostVoted($limit = 3) {
		if (! $limit) {
			return array ();
		}
		
		$pTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		
		$select = $pTable->select ()->where ( 'vote_count > 0' )->where ( 'challenge_id = ?', $this->getIdentity () )->order ( 'vote_count DESC' )->limit ( $limit );
		
		return Zend_Paginator::factory ( $select );
	}
	
	public function getLeaders($limit = 3) {
		if (! $limit) {
			return array ();
		}
		
		$params = array ('ipp' => $limit, 'challenge_id' => $this->getIdentity (), 'sort' => 'most-rated', 'list' => 'leaders', 'period' => 'active' );
		
		$pTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		return $pTable->getPaginator ( $params );
	}
	
	public function isParticipated(User_Model_User $user, $exceptId = 0) {
		$participantTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$select = $participantTable->select ()->where ( 'challenge_id = ?', $this->getIdentity () )->where ( 'user_id = ?', $user->getIdentity () );
		
		if ($exceptId) {
			$select->where ( 'participant_id <> ?', $exceptId );
		}
		
		return ( bool ) $participantTable->fetchRow ( $select );
	}
	
	public function getParticipantInfo(User_Model_User $user) {
		$participantTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$select = $participantTable->select ()->where ( 'challenge_id = ?', $this->getIdentity () )->where ( 'user_id = ?', $user->getIdentity () );
		
		return $participantTable->fetchRow ( $select );
	}
	
	public function getKeywords() {
		return $this->keywords;
	}
	
	public function finishVoting() {
		$this->is_finished = 1;
		$this->save ();
		
		$owner = $this->getOwner ();
		$activityApi = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' );
		$action = $activityApi->addActivity ( $owner, $this, 'vote_challenge_finish' );
		
		return $this;
	}
	
	public function startVoting() {
		$this->is_started = 1;
		$this->save ();
		
		$owner = $this->getOwner ();
		$activityApi = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' );
		$action = $activityApi->addActivity ( $owner, $this, 'vote_challenge_start' );
		
		return $this;
	}
	
	public function isStarted($update = true) {
		if ($this->is_finished) {
			return false;
		}
		
		if ($this->is_started) {
			return true;
		}
		
		$result = ( bool ) (strtotime ( $this->starttime ) < time () && strtotime ( $this->endtime ) > time ());
		if ($result && $update) {
			$this->startVoting ();
		}
		
		return $result;
	}
	
	public function isFinished($update = true) {
		if ($this->is_finished) {
			return true;
		}
		
		$result = ( bool ) (strtotime ( $this->endtime ) < time ());
		
		if ($result && $update) {
			$this->finishVoting ();
		}
		
		return $result;
	}
	
	protected function _delete() {
		$pTable = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$pSelect = $pTable->select ()->where ( 'challenge_id = ?', $this->getIdentity () );
		$participants = $pTable->fetchAll ( $pSelect );
		foreach ( $participants as $participant ) {
			$participant->delete ();
		}
		
		$this->removePhotos ();
		parent::_delete ();
	}
	
	public function removePhotos() {
		if (isset ( $this->photo_id ) && $this->photo_id != 0) {
			$storage = Engine_Api::_ ()->storage ();
			$file = $storage->get ( $this->photo_id );
			if ($file !== null)
				$file->remove ();
			
			$file = $storage->get ( $this->photo_id, 'thumb.profile' );
			if ($file !== null)
				$file->remove ();
			
			$file = $storage->get ( $this->photo_id, 'thumb.normal' );
			if ($file !== null)
				$file->remove ();
			
			$file = $storage->get ( $this->photo_id, 'thumb.icon' );
			if ($file !== null)
				$file->remove ();
		}
	}
	
	public function likes() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'likes', 'core' ) );
	}
	
	public function comments() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'comments', 'core' ) );
	}
	
	public function tags() {
		return new Engine_ProxyObject ( $this, Engine_Api::_ ()->getDbtable ( 'tags', 'core' ) );
	}

}